//
//  ExPrintViewController.swift
//  Swift-Example
//
//  Created by apang on 2018/8/24.
//  Copyright © 2018 apang.men All rights reserved.
//

import UIKit
import WebKit

//参考地址
//http://nshipster.cn/uiprintinteractioncontroller/
//https://blog.csdn.net/openglnewbee/article/details/50498475

class ExPrintViewController: UIViewController {

    @IBOutlet weak var webView: WKWebView!
    var data:Data?
    var fileUrl:URL? = nil
    override func viewDidLoad() {
        super.viewDidLoad()
        let filePath = Bundle.main.path(forResource: "PopinSwift", ofType: "pdf", inDirectory: "Resource/Document")
        fileUrl = URL(fileURLWithPath: filePath!)
        let urlRequest:URLRequest = URLRequest(url: fileUrl!)
        webView.load(urlRequest)
        // Do any additional setup after loading the view.
        do {
            try data = Data(contentsOf: fileUrl!)
        } catch  {
            print("read content fail", "读取失败")
        }
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        (UIApplication.shared.delegate as! AppDelegate).interfacceOrientaion = [.landscapeLeft]
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */
    @IBAction func showPrintUI(_ sender: Any) {
        let printVC:UIPrintInteractionController? = UIPrintInteractionController.shared
        if (printVC != nil){
            printVC?.delegate = self
            let printInfo:UIPrintInfo? = UIPrintInfo.printInfo()
            printInfo?.outputType = .general
            printInfo?.orientation = UIPrintInfo.Orientation.landscape
            printInfo?.jobName = "PrintTest"
            printVC?.printInfo = printInfo
//            printVC?.printingItem = data //可用，数据
            printVC?.printingItem = fileUrl //可用，文件路径 建议使用
            
            //打印webView 不建议使用
//            let viewFormatter = webView.viewPrintFormatter()
//            viewFormatter.startPage = 0
//            printVC?.printFormatter = viewFormatter
            printVC?.present(animated: true, completionHandler: { (vc, completed, error) in
                print((completed ? "完成" : "未完成"),error as Any)
            })
        }else{
            print("无法打印")
        }
    }
    
    @IBAction func printNonUI(_ sender: UIBarButtonItem) {
        if((ExPrinterModel.shared.printer) != nil){
            //正常进入打印流程
            nonUIPrintAction(printItem: fileUrl as Any)
        }else {//需要选择一次设备，然后记录下来
            let printPicker = UIPrinterPickerController(initiallySelectedPrinter: nil)
            printPicker.present(from: self.view.bounds, in: self.view, animated: true) { (printerVC, completed, error) in
                if completed {
                    ExPrinterModel.shared.printer = printerVC.selectedPrinter
                    print("设备名:",printerVC.selectedPrinter?.displayName as Any,"设备地址:",printerVC.selectedPrinter?.url as Any)
                    self.nonUIPrintAction(printItem: self.fileUrl as Any)
                }
            }
        }
    }
    
    func nonUIPrintAction(printItem: Any) {
        let printVC:UIPrintInteractionController? = UIPrintInteractionController.shared
        if (printVC != nil){
            let printInfo:UIPrintInfo? = UIPrintInfo.printInfo()
            printInfo?.outputType = .general
            printInfo?.orientation = UIPrintInfo.Orientation.landscape
            printInfo?.jobName = "PrintTest"
            printVC?.printInfo = printInfo
            printVC?.printingItem = printItem
            printVC?.print(to: ExPrinterModel.shared.printer!, completionHandler: { (vc, completed, error) in
                print((completed ? "完成" : "未完成"),error as Any)
            })
        }
    }
}

extension ExPrintViewController : UIPrintInteractionControllerDelegate {
    
}
